import {
	mapState
} from 'vuex'
import store from "@/store"
import {
	baseURL,
	platform
} from '@/common/config.js';

// 尝试将用户在根目录中的store/index.js的vuex的state变量，全部加载到全局变量中
let $uStoreKey = [];
try {
	$uStoreKey = store.state ? Object.keys(store.state) : [];
} catch (e) {

}

module.exports = {
	methods: {
		navBack() {
			uni.navigateBack({
				fail: () => {
					uni.switchTab({
						url: '/pages/index/index'
					})
				}
			})
		},
		uploader(path) {
			setTimeout(() => {
				uni.showLoading({
					title: '上传中。。。',
					mask: true
				})
			}, 300)
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: baseURL + '/api/common/upload', //仅为示例，非真实的接口地址
					filePath: path,
					header: {
						Token: this.vuex_token,
						platform: platform,
                        uniacid: uni.getStorageSync("uniacid"),
					},
					name: 'file',
					success: uploadFileRes => {
                        uni.hideLoading();
						let r = JSON.parse(uploadFileRes.data);
						if (r.code > 200) {
							setTimeout(() => {
								this.$u.toast(r.msg)
							}, 300)
							reject(r.msg)
						} else {
							resolve(r.data.fullurl)
						}
					},
					fail: (e) => {
						setTimeout(() => {
							this.$u.toast(e.errMsg)
						}, 300)
						reject(e)
					}
				});
			})
		}
	},
	created() {
		// 将vuex方法挂在到$u中
		// 使用方法为：如果要修改vuex的state中的user.name变量为"史诗" => this.$u.vuex('user.name', '史诗')
		// 如果要修改vuex的state的version变量为1.0.1 => this.$u.vuex('version', '1.0.1')
		this.$u.vuex = (name, value) => {
			this.$store.commit('$uStore', {
				name,
				value
			})
		}
	},
	computed: {
		// 将vuex的state中的所有变量，解构到全局混入的mixin中
		...mapState($uStoreKey)
	}
}
